#include <htc.h> 

/* Basic A2D sample code for an PIC16F688 device.
 * This code willl set up the A2D module to return an
 * 8-Bit result. If greater precision is needed, a 10-Bit
 * result can be returned if read_a2d() is modified to
 * return the short ((ADRESH<<8)+(ADRESL)). Note also that
 * ADCON1 should be set to 0x80 in the init_a2d() routine
 * instead of zero.
 *
 *
 * This project can be demonstrated on the Microchip PICDEM2 board.
 */

/* Sample code to set up the A2D module */
void init_a2d(void){
	ADFM = 0;
	VCFG = 0;

	ADCS0 = 0;
	ADCS1 = 0;
	ADCS2 = 0;

	CHS0 = 0;
	CHS1 = 0;
	CHS2 = 0;
	CHS3 = 0;
	
	GODONE=0;	// initiate conversion on the selected channel
	ADON=1;		// turn on the A2D conversion module
}

/* Return an 8 bit result */
unsigned char read_a2d(unsigned char channel){

	channel&=0b00001111;	// truncate channel to 4 bits - channels 0-11 ignore 12-15 

	// clear current channel select
	ADCS0 = 0;
	ADCS1 = 0;
	ADCS2 = 0;

	//if ADFM AND VCFG were a 1 then leave them but the channel select and GODONE and ADON must be cleared
	//before setting the channel desired
	ADCON0&=0b11000001;
	ADCON0|=(channel<<2);	// apply the new channel select

	// initiate conversion on the selected channel
	GODONE = 1;

	while(GODONE)continue;
	return(ADRESH);	// return 8 MSB of the result
}
